<template>
  <div :class="className" :style="{ height: height, width: width }" />
</template>

<script>
var echarts = require('echarts/lib/echarts')
// 引入 ECharts 主模块
require('echarts/lib/chart/bar')
// 引入提示框和标题组件
require('echarts/lib/component/tooltip')
require('echarts/lib/component/title')
require('echarts/lib/component/legend')
require('echarts/lib/component/dataZoom')
// require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { themeColor } from '@/assets/echarts/theme'

export default {
  name: 'AxisChart',
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '400px'
    },
    barData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      chart: null
    }
  },
  watch: {
    barData: {
      handler() {
        this.initChart()
      }
    }
  },
  mounted() {
    this.initChart()
    this.__resizeHandler = debounce(() => {
      if (this.chart) {
        this.chart.resize()
      }
    }, 100)
    window.addEventListener('resize', this.__resizeHandler)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'themeColor')
      this.chart.setOption({
        color: themeColor,
        tooltip: {
          trigger: 'axis',
          axisPointer: { // 坐标轴指示器，坐标轴触发有效
            type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          containLabel: true
        },
        xAxis: [
          {
            name: '工位',
            type: 'category',
            data: this.barData.xKey,
            axisTick: {
              alignWithLabel: true
            },
            axisLabel: {
              isntrval: 0,
              fontSize: 10,
              showMinLabel: true,
              rotate: 40,
              formatter: function(value) {
                const reg = /.{1,24}/g
                return value.length > 23 ? value.match(reg)[0] + '...' : value
              }
            }
          }
        ],
        yAxis: [
          {
            name: '效率(%)',
            type: 'value'
          }
        ],
        series: [
          {
            name: '生产效率',
            type: 'bar',
            barWidth: '60%',
            label: {
              show: true,
              position: 'top'
            },
            data: this.barData.yValue
          }
        ],
        dataZoom: [
          {
            show: true,
            start: 0,
            end: 60
          },
          {
            type: 'inside',
            start: 0,
            end: 60
          }
        ]
      })
    }
  }
}
</script>
